﻿(function() {
    var windowWidth = 0;
    var windowHeight = 0;
    var lastWindowHeight = 0;

    nova.application = {
        histories: new Array(),
        currentPage: null,
        settings: {            
            
        },
        isTouchable: false,
        isIOS: false,
        start: function(url) {
            var obj = this;
            obj.events.backButton(function(e) {
                if (obj.currentPage.isBackbuttonDisabled) {
                    return;
                }
                if (obj.currentPage.backbuttonHandlers.length == 0) {
                    obj.goBack();
                } else {
                    var handler = obj.currentPage.backbuttonHandlers.pop();
                    handler();
                }
            });
            obj.events.onOrientationChanged(function(width, height) {
                if (obj.currentPage && obj.currentPage.onOrientationChanged) {
                    obj.currentPage.onOrientationChanged(width, height);
                }
            });

            console.log("obj started from: " + url);
            $("#body").height($(window).height() + "px");
            initPlatformInformation();

            windowWidth = null;
            windowHeight = $(document).height();
            lastWindowHeight = windowHeight;

            obj.gotoPage(url);
        },
        gotoPage: function(pageOrUrl) {
            var obj = this;
            var page = null;

            if (pageOrUrl instanceof nova.Page) {
                page = pageOrUrl;
            } else {
                page = new nova.Page(pageOrUrl);
            }

            if (obj.currentPage != null) {
                obj.currentPage.onNavigatingAway(function() {
                    if (obj.currentPage.needAddingToHistory) {
                        obj.histories.push(obj.currentPage.clone());
                    }
                    loadNewPage();
                });
            } else {
                loadNewPage();
            }

            function loadNewPage() {
                page.onViewLoaded(function() {
                    var oldPage = obj.currentPage;
                    obj.currentPage = page;
                    obj.onPageChanged(oldPage, obj.currentPage);
                });
                page.load();
            }
        },
        onPageChanged: function(oldPage, newPage) {

        },
        goBack: function(urlUntil) {
            var obj = this;
            if (obj.histories.length == 0) {
                if (obj.isIOS == false) {
                    navigator.notification.confirm("Are you sure you want to exit the app?", function(btnNumber) {
                        if (btnNumber == 1) {
                            nova.application.exit();
                        }
                    }, 'Confirm', 'Exit,Cancel');
                }
                return;
            }
            var page = this.histories.pop();
            if (urlUntil != undefined) {
                while (page.url != urlUntil && this.histories.length > 0) {
                    page = this.histories.pop();
                }
            }
            obj.currentPage.onNavigatingAway(function() {
                var previousPage = obj.currentPage;
                obj.currentPage = page;
                obj.currentPage.onViewLoaded(function() {
                    obj.onPageChanged(previousPage, page);
                });
                obj.currentPage.load();
            });
        },
        exit: function() {
            navigator.app.exitApp();
        },
        isOverflowScrollSupported: function() {
            return this.isTouchable == false;
        },
        events: {
            deviceReady: function(callback) {
                document.addEventListener("deviceready", callback, false);
            },
            backButton: function(callback) {
                document.addEventListener("backbutton", callback, false);
            },
            menuButton: function(callback) {
                document.addEventListener("menubutton", callback, false);
            },
            pause: function(callback) {
                document.addEventListener("pause", callback, false);
            },
            resume: function(callback) {
                document.addEventListener("resume", callback, false);
            },
            searchButton: function(callback) {
                document.addEventListener("searchbutton", callback, false);
            },
            online: function(callback) {
                document.addEventListener("online", callback, false);
            },
            offline: function(callback) {
                document.addEventListener("offline", callback, false);
            },
            batteryCritical: function(callback) {
                document.addEventListener("batterycritical", callback, false);
            },
            batteryLow: function(callback) {
                document.addEventListener("batterylow", callback, false);
            },
            batteryStatus: function(callback) {
                document.addEventListener("batterystatus", callback, false);
            },
            startCallButton: function(callback) {
                document.addEventListener("startcallbutton", callback, false);
            },
            endCallButton: function(callback) {
                document.addEventListener("endcallbutton", callback, false);
            },
            volumeDownButton: function(callback) {
                document.addEventListener("volumedownbutton", callback, false);
            },
            volumeUpButton: function(callback) {
                document.addEventListener("volumeupbutton", callback, false);
            },
            onOrientationChanged: function(callback) {
                $(window).bind('orientationchange', function() {
                    if (windowHeight == lastWindowHeight) {
                        calculateWindowWidth(function() {
                            callback(windowHeight, windowWidth);
                            lastWindowHeight = windowWidth;
                        });
                    } else {
                        calculateWindowWidth(function() {
                            callback(windowWidth, windowHeight);
                            lastWindowHeight = windowHeight;
                        });
                    }
                });
            }
        }
    };

    // private methods -----------------------------------
    
    function initPlatformInformation() {
        var iosDevices = ['iphone', 'ipad', 'ipod'];
        var touchDevices = ['android', 'phone', 'blackbery'].concat(iosDevices);
        var appVersion = navigator.appVersion.toLowerCase();
        for (var i = 0; i < touchDevices.length; i++) {
            if (appVersion.indexOf(touchDevices[i]) > -1) {
                nova.application.isTouchable = true;
                break;
            }
        }
        for (var j = 0; j < iosDevices.length; j++) {
            if (appVersion.indexOf(iosDevices[j]) > -1) {
                nova.application.isIOS = true;
                break;
            }
        }
    }
    
    function calculateWindowWidth(widthCallback) {
        if (windowWidth != null) {
            widthCallback();
            return;
        }
        var counter = 0;
        var timer = setInterval(function () {
            if (counter >= 50) {
                windowWidth = windowHeight;
                clearInterval(timer);
                widthCallback();
                return;
            }
            var height = $(window).height();
            if (height != windowHeight) {
                if (height == windowWidth) {
                    clearInterval(timer);
                    widthCallback();
                } else {
                    windowWidth = height;
                }
            }
            counter++;
        }, 50);
    }

})();


